package me.numark.fragments;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.picasso.Picasso;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Date;

import me.numark.ChatActivity;
import me.numark.ContactsActivity;
import me.numark.MyCommentsActivity;
import me.numark.ProfileActivity;
import me.numark.R;
import me.numark.providers.Numa;
import me.numark.utils.Constants;
import me.numark.utils.MessageUtils;
import me.numark.utils.Utils;

/**
 * Created by tian on 14-9-18:上午7:44.
 */
public class MessagesFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>,
        PullToRefreshBase.OnRefreshListener2, AdapterView.OnItemClickListener {

    private PullToRefreshListView mList;

    DialogAdapter mAdapter;

    NotificationManager notificationManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_message, container, false);
        ((TextView) v.findViewById(R.id.title)).setText(R.string.message);
        v.findViewById(R.id.back).setVisibility(View.GONE);
        v.findViewById(R.id.right_image).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), ContactsActivity.class));
            }
        });
        ((ImageView) v.findViewById(R.id.right_image)).setImageResource(R.drawable.new_msg);
        mList = (PullToRefreshListView) v.findViewById(R.id.ptr_list);
        mAdapter = new DialogAdapter(getActivity());
        mList.setAdapter(mAdapter);
        mList.setOnRefreshListener(this);
        getLoaderManager().initLoader(0, null, this);
        mList.setState(PullToRefreshBase.State.INIT_REFRESHING, true);
        mList.getRefreshableView().setOnItemClickListener(this);
        return v;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (notificationManager == null) {
            notificationManager = (NotificationManager) getActivity()
                    .getSystemService(Context.NOTIFICATION_SERVICE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        notificationManager.cancelAll();
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(getActivity(), Numa.DialogColumns.CONTENT_URI, null, null, null,
                "last_time desc, _id desc");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        mAdapter.swapCursor(cursor);
        notificationManager.cancelAll();
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        mAdapter.swapCursor(null);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                MessageUtils.msgUpdate(getActivity());
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                mList.onRefreshComplete();
            }
        }.execute();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                long time = Constants.BIG_TIME;
                int id = 0;
                if (mAdapter.getCount() > 1) {
                    Cursor cursor = (Cursor) mAdapter.getItem(mAdapter.getCount() - 1);
                    time = cursor.getLong(cursor.getColumnIndex("last_time"));
                    id = cursor.getInt(cursor.getColumnIndex("_id"));
                }
                MessageUtils.loadMoreDialogs(getActivity().getContentResolver(), time, id);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                mList.onRefreshComplete();
            }
        }.execute();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int pos = position - 1;
        Cursor cursor = (Cursor) mAdapter.getItem(pos);
        long cid = cursor.getInt(cursor.getColumnIndex("_id"));
        if (cid == 0) {
            Intent intent = new Intent(getActivity(), MyCommentsActivity.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(getActivity(), ChatActivity.class);
            intent.putExtra(ChatActivity.EXTRA_DID, cid);
            startActivity(intent);
        }
    }


    class DialogAdapter extends CursorAdapter implements View.OnClickListener {

        public DialogAdapter(Context context) {
            super(context, null, 0);
        }

        @Override
        public int getItemViewType(int position) {
            return super.getItemViewType(position);
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            long cid = cursor.getInt(cursor.getColumnIndex("_id"));
            if (cid == 0) {
                return getActivity().getLayoutInflater()
                        .inflate(R.layout.dialog_list_item2, parent, false);
            }
            return getActivity().getLayoutInflater()
                    .inflate(R.layout.dialog_list_item, parent, false);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            long cid = cursor.getInt(cursor.getColumnIndex("_id"));
            int badge = cursor.getInt(cursor.getColumnIndex("badge"));
            if (cid == 0) {
                TextView tv = (TextView) view.findViewById(R.id.unread_count);
                if (badge > 0) {
                    tv.setVisibility(View.VISIBLE);
                    if (badge > 99) {
                        tv.setText("99+");
                    } else {
                        tv.setText(String.valueOf(badge));
                    }
                } else {
                    tv.setVisibility(View.GONE);
                }
                return;
            }
            ImageView avatar = (ImageView) view.findViewById(R.id.messages_avatar);
            Picasso.with(getActivity()).load(cursor.getString(cursor.getColumnIndex("pic")))
                    .into(avatar);
            String uid = cursor.getString(cursor.getColumnIndex("uid"));
            avatar.setTag(uid);
            avatar.setOnClickListener(this);
            TextView tv = (TextView) view.findViewById(R.id.dialog_nick);
            tv.setText(cursor.getString(cursor.getColumnIndex("nick")));
            tv = (TextView) view.findViewById(R.id.dialog_time);
            long time = cursor.getLong(cursor.getColumnIndex("last_time"));
            tv.setText(Utils.getTimeShowText(new Date(time)));
            tv = (TextView) view.findViewById(R.id.dialog_content);
            tv.setText(cursor.getString(cursor.getColumnIndex("last_text")));
            View unread = view.findViewById(R.id.dialog_unread);
            unread.setVisibility(badge > 0 ? View.VISIBLE : View.GONE);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.messages_avatar: {
                    Intent intent = new Intent(getActivity(), ProfileActivity.class);
                    intent.putExtra(ProfileActivity.EXTRA_UID, (String) v.getTag());
                    startActivity(intent);
                }
                break;
            }
        }
    }
}
